home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / deskbar-applet / handlers / galeon.py < prev    next >
Encoding:
Python Source  |  2007-04-09  |  8.4 KB  |  296 lines

  1. import xml.sax, traceback
  2. import re, urllib
  3. from os.path import join, expanduser, exists
  4. from gettext import gettext as _
  5. import gtk
  6. import gnomevfs
  7. import deskbar, deskbar.Indexer, deskbar.Handler
  8. from deskbar.Watcher import FileWatcher
  9. from deskbar.BrowserMatch import get_url_host, is_preferred_browser
  10. from deskbar.BrowserMatch import BrowserSmartMatch, BrowserMatch
  11. from deskbar.defs import VERSION
  12.  
  13. def _check_requirements():
  14. #    if deskbar.UNINSTALLED_DESKBAR:
  15. #        return (deskbar.Handler.HANDLER_IS_HAPPY, None, None)
  16.         
  17.     if is_preferred_browser("galeon"):
  18.         return (deskbar.Handler.HANDLER_IS_HAPPY, None, None)
  19.     else:
  20.         return (deskbar.Handler.HANDLER_IS_NOT_APPLICABLE, "Galeon is not your preferred browser, not using it.", None)
  21.         
  22. HANDLERS = {
  23.     "GaleonBookmarksHandler" : {
  24.         "name": _("Web Bookmarks"),
  25.         "description": _("Open your web bookmarks by name"),
  26.         "requirements": _check_requirements,
  27.         "version": VERSION,
  28.     },
  29.     "GaleonHistoryHandler" : {
  30.         "name": _("Web History"),
  31.         "description": _("Open your web history by name"),
  32.         "requirements": _check_requirements,
  33.         "version": VERSION,
  34.     },
  35.     "GaleonSearchHandler" : {
  36.         "name": _("Web Searches"),
  37.         "description": _("Search the web via your browser's search settings"),
  38.         "requirements": _check_requirements,
  39.         "version": VERSION,
  40.     },
  41. }
  42.  
  43. GALEON_HISTORY_FILE = expanduser("~/.galeon/history2.xml")
  44. if not exists(GALEON_HISTORY_FILE):
  45.     GALEON_HISTORY_FILE = expanduser("~/.galeon/history.xml")
  46. GALEON_BOOKMARKS_FILE = expanduser("~/.galeon/bookmarks.xbel")
  47.  
  48. favicon_cache = None
  49. bookmarks = None
  50. smart_bookmarks = None
  51. quicksearches = None
  52.  
  53. class GaleonHandler(deskbar.Handler.Handler):
  54.     def __init__(self, watched_file, callback, icon="stock_bookmark"):
  55.         deskbar.Handler.Handler.__init__(self, icon)
  56.         self.watched_file = watched_file
  57.         self.watch_callback = callback
  58.         
  59.     def initialize(self):
  60.         global favicon_cache
  61.         
  62.         if not hasattr(self, 'watcher'):
  63.             self.watcher = FileWatcher()
  64.             self.watcher.connect('changed', lambda watcher, f: self.watch_callback())
  65.             
  66.         self.watcher.add(self.watched_file)
  67.         
  68.         if favicon_cache == None:
  69.             favicon_cache = GaleonFaviconCacheParser().get_cache()
  70.     
  71.     def stop(self):
  72.         self.watcher.remove(self.watched_file)
  73.         
  74. class GaleonBookmarksHandler(GaleonHandler):
  75.     def __init__(self):
  76.         GaleonHandler.__init__(self, GALEON_BOOKMARKS_FILE, lambda: self._parse_bookmarks(True))
  77.     
  78.     def initialize(self):
  79.         GaleonHandler.initialize(self)
  80.         self._parse_bookmarks()
  81.     
  82.     def _parse_bookmarks(self, force=False):
  83.         global favicon_cache, bookmarks, smart_bookmarks, quicksearches
  84.         if force or bookmarks == None:
  85.             parser = GaleonBookmarksParser(self, favicon_cache)
  86.             bookmarks = parser.get_indexer()
  87.             smart_bookmarks = parser.get_smart_bookmarks()
  88.             quicksearches = parser.get_quicksearches()
  89.     
  90.     def query(self, query):
  91.         global bookmarks
  92.         return bookmarks.look_up(query)[:deskbar.DEFAULT_RESULTS_PER_HANDLER]
  93.  
  94. class GaleonSearchHandler(GaleonBookmarksHandler):
  95.     def __init__(self):
  96.         GaleonBookmarksHandler.__init__(self)
  97.     
  98.     def query(self, query):
  99.         global smart_bookmarks
  100.         global quicksearches
  101.         query_a = query.split(" ")
  102.         if len(query_a) > 1 and quicksearches.has_key(query_a[0]):
  103.             return (quicksearches[query_a[0]],)
  104.         else:
  105.             return smart_bookmarks
  106.         
  107. class GaleonHistoryHandler(GaleonHandler):
  108.     def __init__(self):
  109.         GaleonHandler.__init__(self, GALEON_HISTORY_FILE, self._parse_history, "epiphany-history.png")
  110.         self._history = None
  111.         
  112.     def initialize(self):
  113.         GaleonHandler.initialize(self)
  114.         self._parse_history()
  115.         
  116.     def _parse_history(self):
  117.         global favicon_cache
  118.         self._history = GaleonHistoryParser(self, favicon_cache).get_indexer()
  119.             
  120.     def query(self, query):
  121.         return self._history.look_up(query)[:deskbar.DEFAULT_RESULTS_PER_HANDLER]
  122.  
  123. class GaleonBookmarksParser(xml.sax.ContentHandler):
  124.     def __init__(self, handler, cache):
  125.         xml.sax.ContentHandler.__init__(self)
  126.         
  127.         self.handler = handler
  128.         
  129.         self.chars = ""
  130.         self.title = None
  131.         self.href = None
  132.         self.smarthref = None
  133.         
  134.         self._indexer = deskbar.Indexer.Indexer()
  135.         self._qsindexer = {}
  136.         self._smart_bookmarks = []
  137.  
  138.         
  139.         self._cache = cache
  140.         self._index_bookmarks()
  141.     
  142.     def get_indexer(self):
  143.         """
  144.         Returns a completed indexer with the contents of bookmark file
  145.         """
  146.         return self._indexer
  147.     
  148.     def get_quicksearches(self):
  149.         return self._qsindexer
  150.     
  151.     def get_smart_bookmarks(self):
  152.         """
  153.         Return a list of GaleonSmartMatch instances representing smart bookmarks
  154.         """
  155.         return self._smart_bookmarks
  156.         
  157.     def _index_bookmarks(self):
  158.         if exists(GALEON_BOOKMARKS_FILE):
  159.             parser = xml.sax.make_parser()
  160.             parser.setContentHandler(self)
  161.             try:
  162.                 parser.parse(GALEON_BOOKMARKS_FILE)
  163.             except Exception, e:
  164.                 print "Failed to parse galeon bookmarks, this is a know bug #338762:", e
  165.                 traceback.print_exc()
  166.     
  167.     def characters(self, chars):
  168.         self.chars = self.chars + chars
  169.         
  170.     def startElement(self, name, attrs):
  171.         self.chars = ""
  172.         if name == "bookmark":
  173.             self.title = None
  174.             self.href = attrs['href'].encode('latin1')
  175.             self.smarthref = None
  176.             self.nick = None
  177.  
  178.     def endElement(self, name):
  179.         if name == "title":
  180.             self.title = self.chars.encode('utf8')
  181.         elif name == "smarturl":
  182.             self.smarthref = self.chars.encode('latin1')
  183.             self.smarthref = re.sub('{.*}','',self.smarthref)
  184.         elif name == "nick":
  185.             self.nick = self.chars.encode('latin1')
  186.         elif name == "bookmark":
  187.             if self.href.startswith("javascript:"):
  188.                 return
  189.             
  190.             img = None
  191.             host = get_url_host(self.href)
  192.             if host in self._cache:
  193.                 img = self._cache[host]
  194.  
  195.             bookmark = BrowserMatch(self.handler, self.title, self.href, icon=img)
  196.             self._indexer.add("%s %s" % (self.title, self.href), bookmark)
  197.             if self.nick != None and self.smarthref != None:
  198.                 quicksearch = BrowserSmartMatch(self.handler, self.title, self.smarthref, icon=img, bookmark=bookmark, prefix_to_strip=self.nick)
  199.                 self._qsindexer[self.nick] = quicksearch
  200.  
  201.             if self.smarthref != None:
  202.                 bookmark = BrowserSmartMatch(self.handler, self.title, self.smarthref, icon=img, bookmark=bookmark)
  203.                 self._smart_bookmarks.append(bookmark)
  204.  
  205. class GaleonFaviconCacheParser(xml.sax.ContentHandler):
  206.     def __init__(self):
  207.         xml.sax.ContentHandler.__init__(self)
  208.         self.galeon_dir = expanduser("~/.galeon/")
  209.         self.filename = join(self.galeon_dir, "favicon_cache.xml")
  210.         
  211.         self.cache = None
  212.         
  213.         self.chars = ""
  214.         self.url = None
  215.         self.name = None
  216.     
  217.     def get_cache(self):
  218.         """
  219.         Returns a dictionary of (host, favicon path) entries where
  220.           host is the hostname, like google.com (without www)
  221.           favicon path is the on-disk path to the favicon image file.
  222.         """
  223.         if self.cache != None:
  224.             return self.cache
  225.         
  226.         self.cache = {}
  227.         if exists(self.filename):
  228.             parser = xml.sax.make_parser()
  229.             parser.setContentHandler(self)
  230.             parser.parse(self.filename)
  231.             
  232.         return self.cache
  233.     
  234.     def characters(self, chars):
  235.         self.chars = self.chars + chars
  236.         
  237.     def startElement(self, name, attrs):
  238.         self.chars = ""
  239.         if name == "entry":
  240.             self.url = attrs['url']
  241.             self.name = attrs['favicon']
  242.  
  243.     def endElement(self, name):
  244.         if name == "entry":
  245.             # Splithost requires //xxxx[:port]/xxxx, so we remove "http:"
  246.             host = get_url_host(self.url)
  247.             self.cache[host] = join(self.galeon_dir, "favicon_cache", self.name.encode('utf8'))
  248.  
  249.  
  250. class GaleonHistoryParser(xml.sax.ContentHandler):
  251.     def __init__(self, handler, cache):
  252.         xml.sax.ContentHandler.__init__(self)
  253.  
  254.         self.handler = handler;
  255.         self._cache = cache;
  256.  
  257.         self._indexer = deskbar.Indexer.Indexer()
  258.  
  259.         self._index_history();
  260.  
  261.     def get_indexer(self):
  262.         """
  263.         Returns a completed indexer with the contents of the history file
  264.         """
  265.         return self._indexer;
  266.  
  267.     def _index_history(self):
  268.         if exists(GALEON_HISTORY_FILE):
  269.             parser = xml.sax.make_parser()
  270.             parser.setContentHandler(self)
  271.             parser.parse(GALEON_HISTORY_FILE)
  272.  
  273.     def startElement(self, name, attrs):
  274.         self.chars = ""
  275.         if name == "item":
  276.             url   = attrs['url'].encode('utf8')
  277.             title = attrs['title'].encode('utf8')
  278.  
  279.             pixbuf = None
  280.             try:
  281.                 host = get_url_host(url)
  282.                 if host in self._cache:
  283.                     pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self._cache[host], deskbar.ICON_HEIGHT, deskbar.ICON_HEIGHT)
  284.             except Exception, msg:
  285.                 # Most of the time we have an html page here, it could also be an unrecognized format
  286.                 print 'Error:endElement(%s):Title:%s:%s' % (name.encode("utf8"), title, msg)
  287.  
  288.             item = BrowserMatch(self.handler, title, url, True, icon=pixbuf)
  289.             self._indexer.add("%s %s" % (title, url), item)
  290.  
  291.     def characters(self, chars):
  292.         None
  293.     
  294.     def endElement(self, name):
  295.         None
  296.